<template>
  <div class="process app-container">
    <!--  客户阶段tab start  -->
    <a-tabs v-model:active-key="searchObj.portraitId" @change="init">
      <a-tab-pane v-for="item in portraitTabs" :key="item.portraitId" :title="item.portraitName"></a-tab-pane>
    </a-tabs>
    <!--  客户阶段tab end  -->

    <!--  添加客户阶段 start  -->
    <div class="head" v-if="portraitTabs.length">
      <a-button type="primary" @click="openStageVisible">
        <template #icon>
          <icon-plus />
        </template>
        添加客户阶段
      </a-button>
      <div class="switch">
        是否展示禁用任务
        <a-switch size="small" v-model="searchObj.showStatus" :unchecked-value="0" :checked-value="1" @change="init" />
      </div>
    </div>
    <!--  添加客户阶段 end  -->

    <!--  外层table start  -->
    <div class="table-head" v-if="tableData.length">
      <a-table :columns="(taskColumns as any)" :pagination="false" :scroll="{ x: 1000 }"></a-table>
    </div>
    <!--  外层table end  -->

    <!--   内层任务列表 start -->
    <div class="table-list" v-if="tableData.length">
      <div
        :class="{ 'table-item': true, 'table-head': item.templateTaskList?.length === 0 }"
        v-for="item in tableData"
        :key="item.stageSettingId"
      >
        <div class="table-title">
          <div>{{ item.stageName }}</div>
          <div class="right">
            <div v-if="!item.templateTaskList || item.templateTaskList?.length == 0" @click="delCustomerStage(item, 'stage')">
              删除
            </div>
            <div v-else-if="!unfoldArr.includes(item.stageSettingId)" @click="unfold(item.stageSettingId)">
              展开更多({{ item.templateTaskList ? item.templateTaskList.length : 0 }})
              <icon-down />
            </div>
            <div v-else-if="unfoldArr.includes(item.stageSettingId)" @click="collapse(item.stageSettingId)">
              收起
              <icon-up />
            </div>
          </div>
        </div>
        <template v-if="unfoldArr.includes(item.stageSettingId)">
          <a-table
            :columns="(taskColumns as any)"
            :data="item.templateTaskList ? item.templateTaskList : []"
            :pagination="false"
            :show-header="false"
            :bordered="{ wrapper: true, cell: true }"
            :scroll="{ x: 1000 }"
          >
            <template #empty></template>
            <template #operate="{ record }">
              <a-button type="text" size="mini" @click="handelEditFlowTask(item, record)">编辑</a-button>
              <a-button type="text" size="mini" @click="handleReferenceData(record)">参考数据</a-button>
              <a-button type="text" size="mini" @click="delCustomerStage(record, 'task')">删除</a-button>
            </template>
            <template #status="{ record }">
              <a-switch v-model="record.status" :unchecked-value="0" :checked-value="1" @change="updateStatus(record)" />
            </template>
            <template #isMust="{ record }">
              {{ record.isMust == 1 ? "是" : "否" }}
            </template>
          </a-table>
          <div class="add" @click="handelAddFlowTask(item)">
            <icon-plus />
            添加任务
          </div>
        </template>
      </div>
    </div>
    <!--  内层任务列表 end  -->

    <div class="empty" v-else>
      <img src="@/assets/images/empty.png" alt="" />
      <div>这里什么都没有{{ !portraitTabs.length ? "，请先配置客户画像" : "" }}</div>
    </div>
  </div>

  <!--  start 删除-->
  <delDialog
    v-if="showDelDialog"
    :currentTaskSettingId="currentTaskSettingId"
    :currentPortraitId="searchObj.portraitId"
    :stageSettingId="stageDetail.stageSettingId"
    :currentDeleteType="currentDeleteType"
    @handleDelete="handleDelete"
  ></delDialog>
  <!--  end 删除-->
  <!-- start 新增阶段 -->
  <addStage v-if="showAddStageDialog" :currentPortraitId="searchObj.portraitId" @handleAddStage="handleAddStage"></addStage>
  <!--  end 新增阶段-->
  <!--  start 新增任务-->
  <addTask
    v-if="showAddTaskDialog"
    :taskEditType="taskEditType"
    :rules="rules"
    :stageDetail="stageDetail"
    :currentTaskSettingId="currentTaskSettingId"
    :currentStageType="currentStageType"
    :currentPortraitId="searchObj.portraitId"
    @handleTask="handleTask"
  ></addTask>
  <!--  end 新增任务-->
  <!--  start 参考数据-->
  <referenceData
    v-if="showReferenceDialog"
    :task-setting-id="taskSettingId"
    @handleReferenceClose="handleReferenceClose"
  ></referenceData>
  <!--  end 参考数据-->
</template>

<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import delDialog from "./process/deleteDialog.vue";
import addStage from "./process/addStageDialog.vue";
import addTask from "./process/addTaskDialog.vue";
import referenceData from "./process/referenceDataDialog.vue";
import { taskColumns } from "@/views/system/components/processConfig/config";
import { businessType, setTaskStatus, taskList } from "@/apis/system";
import type { ProcessParams, ProcessListItem, CustomerProfilingItem, ProcessTaskItem } from "@/apis/system/type";

defineProps(["rules"]);

//业务类型tab模块
const portraitTabs = ref<CustomerProfilingItem[]>([]);
/**
 * 获取业务类型-原客户画像
 */
const searchObj = ref<ProcessParams>({
  portraitId: "",
  showStatus: 0
});
const getPortrait = async () => {
  const res = await businessType();
  portraitTabs.value = res.data || [];
  searchObj.value.portraitId = searchObj.value.portraitId == "" ? (res.data[0].portraitId as string) : searchObj.value.portraitId;
  init();
};

/**
 * 表格模块
 */
const unfoldArr = ref<any[]>([]);
const tableData = ref<any[]>([]);
const init = async () => {
  const { portraitId, showStatus } = searchObj.value;
  const res = await taskList(portraitId, { status: showStatus == 0 ? 1 : 0 });
  tableData.value = res.data || [];
  // tableData.value = [{ templateTaskList: [{}, {}], stageName: "" }, { templateTaskList: [] }];
  unfoldArr.value = tableData.value.map(v => v.stageSettingId);
};
/**
 * 展开表格
 * @param id 展开表格key
 */
const unfold = (id: string) => {
  unfoldArr.value.push(id);
};
/**
 * 收起表格
 * @param id 收起的表格key
 */
const collapse = (id: string) => {
  unfoldArr.value.splice(unfoldArr.value.indexOf(id), 1);
};
const updateStatus = async (item: ProcessTaskItem) => {
  try {
    await setTaskStatus(item.taskSettingId, item.status);
    Message.success("操作成功");
    init();
  } catch (err) {
    item.status = item.status == 1 ? 0 : 1;
  }
};

//阶段模块
const showAddStageDialog = ref(false);
const openStageVisible = () => {
  showAddStageDialog.value = true;
};
const handleAddStage = (type: string) => {
  showAddStageDialog.value = false;
  if (type == "confirm") {
    init();
  }
};

//任务模块
//删除任务
const showDelDialog = ref(false);
const currentDeleteType = ref("");
const delCustomerStage = async (item: any, type: string) => {
  currentDeleteType.value = type;
  if (type == "task") {
    currentTaskSettingId.value = item.taskSettingId;
  }
  if (type == "stage") {
    stageDetail.value = { stageName: item.stageName, stageSettingId: item.stageSettingId };
  }
  showDelDialog.value = true;
};
const handleDelete = (type: string) => {
  showDelDialog.value = false;
  if (type == "confirm") {
    init();
  }
};
//新增任务
const taskEditType = ref("add");
const showAddTaskDialog = ref(false);
const currentTaskSettingId = ref("");
const currentStageType = ref("");
const handelAddFlowTask = (stage: ProcessListItem) => {
  taskEditType.value = "add";
  showAddTaskDialog.value = true;
  currentStageType.value = stage.stageType;
  // stageDetail.value = {stageName: '测试',stageSettingId:'1'}
  stageDetail.value = { stageName: stage.stageName, stageSettingId: stage.stageSettingId };
};
const handelEditFlowTask = async (stage: ProcessListItem, process: ProcessTaskItem) => {
  if (!process || !process.taskSettingId) {
    return Message.error("请选择要编辑的任务");
  }
  currentTaskSettingId.value = process.taskSettingId;
  currentStageType.value = stage.stageType;
  taskEditType.value = "edit";
  stageDetail.value = { stageName: stage.stageName, stageSettingId: stage.stageSettingId };
  showAddTaskDialog.value = true;
};

// 任务详情--阶段名称
const stageDetail = ref({
  stageName: "",
  stageSettingId: ""
});
const handleTask = () => {
  showAddTaskDialog.value = false;
  init();
};

/**
 * 参考数据
 */
const showReferenceDialog = ref(false);
const taskSettingId = ref("");
const handleReferenceData = (record: any) => {
  showReferenceDialog.value = true;
  taskSettingId.value = record.taskSettingId;
};
const handleReferenceClose = () => {
  showReferenceDialog.value = false;
};

onMounted(() => {
  // console.log("mount")
  getPortrait();
});
</script>

<style scoped lang="scss">
@import "process";
</style>
